﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Template.Core.Utils.JWT;

namespace Template.Core.Filter
{
    /// <summary>
    /// 权限控制器
    /// </summary>
    public class AuthFilter : Attribute, IAuthorizationFilter
    {
        /// <summary>
        /// 拦截验证(主要用于JWT)
        /// </summary>
        /// <param name="context"></param>
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //是否不需要拦截
            if (context.Filters.Any(item => item is IAllowAnonymousFilter))
            {
                return;
            }
            else
            {
                //判断是否有token值
                bool flag = context.HttpContext.Request.Headers.ContainsKey("Authorization");
                if (!flag)//如果没有则返回没有权限
                {
                    context.Result = new JsonResult(new { message = "Unauthorized" })
                    { StatusCode = StatusCodes.Status401Unauthorized };
                }
                else
                {
                    //获取token值
                    var token = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
                        ?? context.HttpContext.Request.Headers["X-Token"].FirstOrDefault()
                        ?? context.HttpContext.Request.Query["Token"].FirstOrDefault()
                        ?? context.HttpContext.Request.Cookies["Token"];
                    //解析token值，并且返回token对象
                    Token tokenUser = JWTHelper.SerializeJWT(token);
                    if (tokenUser == null && tokenUser.Role == null)
                    {
                        context.Result = new JsonResult(new { message = "Unauthorized" })
                        { StatusCode = StatusCodes.Status401Unauthorized };
                    }
                }
            }
        }
    }
}
